<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>类别管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .modal-backdrop {
            z-index: 1040 !important;
        }
        .modal-content {
            z-index: 1050 !important;
        }
    </style>
</head>
<body>
<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">类别管理</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
            <i class="fa fa-plus me-2"></i>添加类别
        </button>
    </div>

    <!-- 类别表格 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-bordered align-middle mb-0" id="categoryTable">
                <thead class="table-light">
                <tr>
                    <th style="width:60px;">#</th>
                    <th>类别名称</th>
                    <th>创建时间</th>
                    <th>更新时间</th>
                    <th style="width:160px;">操作</th>
                </tr>
                </thead>
                <tbody>
                <!-- JS填充 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加类别模态框 -->
    <div class="modal fade" id="addCategoryModal" tabindex="-1" aria-labelledby="addCategoryModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addCategoryModalLabel">添加类别</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="text" class="form-control" id="categoryNameInput" placeholder="请输入类别名称">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="addCategoryBtn">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑类别模态框 -->
    <div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editCategoryModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editCategoryModalLabel">编辑类别</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="text" class="form-control" id="editCategoryNameInput" placeholder="请输入类别名称">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveEditCategoryBtn">保存</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="/jquery-3.7.1.min.js"></script>
<script>
    // 类别数据（后端接口获取）
    let categories = [];
    let editId = null;

    function renderTable() {
        const tbody = document.querySelector('#categoryTable tbody');
        tbody.innerHTML = '';
        categories.forEach((cat, idx) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${cat.id}</td>
                <td>${cat.name}</td>
                <td>${cat.createdAt || ''}</td>
                <td>${cat.updatedAt || ''}</td>
                <td>
                    <button class="btn btn-sm btn-warning me-2 edit-btn"><i class="fa fa-pencil"></i> 编辑</button>
                    <button class="btn btn-sm btn-danger delete-btn"><i class="fa fa-trash"></i> 删除</button>
                </td>`;
            // 绑定事件
            $(tr).find('.edit-btn').click(function () {
                editId = cat.id;
                $('#editCategoryNameInput').val(cat.name);
                const modal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
                modal.show();
            });
            $(tr).find('.delete-btn').click(function () {
                if (confirm('确定要删除该类别吗？')) {
                    $.ajax({
                        url: 'http://localhost:8082/api/tags/' + cat.id,
                        method: 'DELETE',
                        success: function(data) {
                            fetchCategories();
                            alert('删除成功！');
                        },
                        error: function() {
                            alert('删除失败');
                        }
                    });
                }
            });
            tbody.appendChild(tr);
        });
    }

    // 获取类别数据
    function fetchCategories() {
        $.ajax({
            url: 'http://localhost:8082/api/tags/',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                if (data.code === 200 && Array.isArray(data.data)) {
                    categories = data.data;
                    renderTable();
                } else {
                    alert('获取类别数据失败');
                }
            },
            error: function() {
                alert('无法连接到类别接口');
            }
        });
    }
    // 添加类别
    document.getElementById('addCategoryBtn').onclick = function () {
        const input = document.getElementById('categoryNameInput');
        const name = input.value.trim();
        if (!name) {
            input.classList.add('is-invalid');
            input.focus();
            return;
        }
        input.classList.remove('is-invalid');
        const btn = this;
        btn.disabled = true;
        btn.textContent = '添加中...';
        $.ajax({
            url: 'http://localhost:8082/api/tags/add',
            method: 'get',
            data: {name},
            dataType: 'json',
            success: function(data) {
                if (data.code === 200) {
                    fetchCategories();
                    input.value = '';
                    const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('addCategoryModal'));
                    modal.hide();
                    alert('添加成功！');
                } else {
                    alert('添加失败：' + (data.msg || '未知错误'));
                }
            },
            error: function() {
                alert('添加失败，无法连接到服务器');
            },
            complete: function() {
                btn.disabled = false;
                btn.textContent = '添加';
            }
        });
    };

    // 编辑保存
    $('#saveEditCategoryBtn').click(function () {
        const input = $('#editCategoryNameInput');
        const name = input.val().trim();
        if (!name) {
            input.addClass('is-invalid');
            input.focus();
            return;
        }
        input.removeClass('is-invalid');
        if (editId !== null) {
            $.ajax({
                url: 'http://localhost:8082/api/tags/' + editId,
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify({ name: name }),
                dataType: 'json',
                success: function(data) {
                    if (data.code === 200) {
                        fetchCategories();
                        const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('editCategoryModal'));
                        modal.hide();
                        alert('编辑成功！');
                    } else {
                        alert('编辑失败：' + (data.msg || '未知错误'));
                    }
                },
                error: function() {
                    alert('编辑失败，无法连接到服务器');
                }
            });
        }
    });

    // 清除输入框校验
    document.getElementById('categoryNameInput').oninput = function () {
        this.classList.remove('is-invalid');
    };
    document.getElementById('editCategoryNameInput').oninput = function () {
        this.classList.remove('is-invalid');
    };

    // 初始化表格（页面加载时拉取数据）
    fetchCategories();
</script>
</body>
</html> 